<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="请求方法" prop="method">
          <el-select v-model="queryParams.method" placeholder="请选择请求方法" clearable>
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
            <el-option label="PATCH" value="PATCH" />
          </el-select>
        </el-form-item>
        <el-form-item label="请求URL" prop="url">
          <el-input v-model="queryParams.url" placeholder="请输入请求URL" clearable />
        </el-form-item>
        <el-form-item label="状态码" prop="status_code">
          <el-select v-model="queryParams.status_code" placeholder="请选择状态码" clearable>
            <el-option label="200" :value="200" />
            <el-option label="400" :value="400" />
            <el-option label="401" :value="401" />
            <el-option label="403" :value="403" />
            <el-option label="404" :value="404" />
            <el-option label="500" :value="500" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleTimeRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
          <el-button @click="handleRefresh" :loading="loading">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card shadow="never" class="table-wrapper">
      <template #header>
        <div class="card-header">
          <span>请求日志</span>
          <div>
            <el-button type="warning" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>清理日志
            </el-button>
          </div>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="logList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="username" label="用户" min-width="100" show-overflow-tooltip />
        <el-table-column prop="method" label="请求方法" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="getMethodTagType(row.method)" size="small">
              {{ row.method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="请求URL" min-width="200" show-overflow-tooltip />
        <el-table-column prop="ip_address" label="客户端IP" width="120" show-overflow-tooltip />
        <el-table-column prop="status_code" label="状态码" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status_code)" size="small">
              {{ row.status_code }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="response_time" label="响应时间" width="100" align="center">
          <template #default="{ row }">
            {{ row.response_time }}ms
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="请求时间" width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">
              <el-icon><View /></el-icon>详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      title="请求日志详情"
      v-model="detailVisible"
      width="800px"
      append-to-body
      destroy-on-close
    >
      <el-descriptions :column="2" border v-if="logDetail">
        <el-descriptions-item label="用户">{{ logDetail.username }}</el-descriptions-item>
        <el-descriptions-item label="请求方法">
          <el-tag :type="getMethodTagType(logDetail.method)" size="small">
            {{ logDetail.method }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请求URL" :span="2">{{ logDetail.path }}</el-descriptions-item>
        <el-descriptions-item label="客户端IP">{{ logDetail.ip_address }}</el-descriptions-item>
        <el-descriptions-item label="状态码">
          <el-tag :type="getStatusTagType(logDetail.status_code)" size="small">
            {{ logDetail.status_code }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="响应时间">{{ logDetail.response_time }}ms</el-descriptions-item>
        <el-descriptions-item label="请求时间">{{ logDetail.created_at }}</el-descriptions-item>
        <el-descriptions-item label="用户代理" :span="2">{{ logDetail.user_agent }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider>请求体</el-divider>
      <el-input
        v-model="logDetail.request_body"
        type="textarea"
        :rows="6"
        readonly
        placeholder="无请求体数据"
      />
      
      <el-divider>响应体</el-divider>
      <el-input
        v-model="logDetail.response_body"
        type="textarea"
        :rows="6"
        readonly
        placeholder="无响应体数据"
      />
    </el-dialog>

    <!-- 批量删除对话框 -->
    <el-dialog
      title="清理日志"
      v-model="deleteDialogVisible"
      width="400px"
      append-to-body
    >
      <el-form :model="deleteForm" label-width="100px">
        <el-form-item label="保留天数">
          <el-input-number
            v-model="deleteForm.days"
            :min="1"
            :max="365"
            placeholder="请输入保留天数"
          />
          <div class="form-tip">将删除 {{ deleteForm.days }} 天前的所有请求日志</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmBatchDelete">确定删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onActivated, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete, View } from '@element-plus/icons-vue'
import { getRequestLogs, getRequestLogDetail, deleteRequestLogsBatch } from '@/api/logs'
import { useThemeStore } from '@/store/theme'

// 主题状态
const themeStore = useThemeStore()

// 查询参数
const queryParams = reactive({
  page: 1,
  page_size: 10,
  method: '',
  url: '',
  status_code: null,
  start_time: '',
  end_time: ''
})

// 时间范围
const timeRange = ref([])

// 表格数据
const logList = ref([])
const total = ref(0)
const loading = ref(false)
const isInitialized = ref(false) // 组件是否已初始化

// 详情相关
const detailVisible = ref(false)
const logDetail = ref(null)

// 批量删除相关
const deleteDialogVisible = ref(false)
const deleteForm = reactive({
  days: 30
})

const queryFormRef = ref(null)

// 获取请求日志列表
const getLogList = async () => {
  loading.value = true
  try {
    const res = await getRequestLogs(queryParams)
    console.log('请求日志数据:', res)
    // 处理后端返回的数据结构
    if (res && res.data) {
      logList.value = res.data.map(item => ({
        ...item,
        created_at: item.created_at ? new Date(item.created_at).toLocaleString() : ''
      }))
      total.value = res.page_info ? res.page_info.total : 0
    } else {
      logList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取请求日志列表失败:', error)
    ElMessage.error('获取请求日志列表失败')
  } finally {
    loading.value = false
  }
}

// 初始化组件（仅在首次激活时加载数据）
const initializeComponent = () => {
  if (!isInitialized.value) {
    getLogList()
    isInitialized.value = true
  }
}

// 处理时间范围变化
const handleTimeRangeChange = (value) => {
  if (value && value.length === 2) {
    queryParams.start_time = value[0]
    queryParams.end_time = value[1]
  } else {
    queryParams.start_time = ''
    queryParams.end_time = ''
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  getLogList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value.resetFields()
  timeRange.value = []
  queryParams.start_time = ''
  queryParams.end_time = ''
  handleQuery()
}

// 手动刷新
const handleRefresh = () => {
  getLogList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getLogList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.page_size = size
  getLogList()
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    console.log('开始获取日志详情，ID:', row.id)
    const res = await getRequestLogDetail(row.id)
    console.log('请求日志详情原始响应:', res)
    
    // 处理详情数据 - 后端返回的数据包装在data字段中
    let detailData = null
    if (res && res.data) {
      detailData = res.data
      console.log('解析后的详情数据:', detailData)
    } else if (res) {
      // 兼容直接返回数据的情况
      detailData = res
      console.log('直接使用响应数据:', detailData)
    }
    
    if (detailData) {
      logDetail.value = {
        ...detailData,
        created_at: detailData.created_at ? new Date(detailData.created_at).toLocaleString() : '',
        request_body: detailData.request_body || '无请求体数据',
        response_body: detailData.response_body || '无响应体数据'
      }
      console.log('最终设置的详情数据:', logDetail.value)
    } else {
      // 如果没有详情数据，使用列表中的数据作为备选
      console.log('使用列表数据作为备选:', row)
      logDetail.value = {
        ...row,
        created_at: row.created_at,
        request_body: '无请求体数据',
        response_body: '无响应体数据'
      }
    }
    detailVisible.value = true
  } catch (error) {
    console.error('获取请求日志详情失败:', error)
    ElMessage.error(`获取请求日志详情失败: ${error.message || error}`)
  }
}

// 批量删除
const handleBatchDelete = () => {
  deleteDialogVisible.value = true
}

// 确认批量删除
const confirmBatchDelete = async () => {
  try {
    const res = await deleteRequestLogsBatch(deleteForm.days)
    ElMessage.success(res.data ? res.data.message : '清理日志成功')
    deleteDialogVisible.value = false
    getLogList()
  } catch (error) {
    console.error('清理日志失败:', error)
    ElMessage.error('清理日志失败')
  }
}

// 获取请求方法标签类型
const getMethodTagType = (method) => {
  const typeMap = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return typeMap[method] || 'info'
}

// 获取状态码标签类型
const getStatusTagType = (statusCode) => {
  if (statusCode >= 200 && statusCode < 300) {
    return 'success'
  } else if (statusCode >= 400 && statusCode < 500) {
    return 'warning'
  } else if (statusCode >= 500) {
    return 'danger'
  }
  return 'info'
}

// 页面激活时的懒加载
onActivated(() => {
  initializeComponent()
})

// 直接访问页面时的初始化
onMounted(() => {
  // 使用 nextTick 确保组件完全挂载后再初始化
  nextTick(() => {
    initializeComponent()
  })
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0;
  
  .search-wrapper {
    margin-bottom: 20px;
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    
    :deep(.el-card__body) {
      background-color: var(--card-bg-color);
      padding: 20px;
    }
    
    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 16px;
        
        .el-form-item__label {
          color: var(--text-color);
          font-weight: 500;
        }
        
        .el-input__wrapper {
          border-radius: 6px;
          transition: all 0.3s ease;
          background-color: var(--card-bg-color);
          
          &:hover {
            border-color: var(--border-color);
          }
          
          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
        
        .el-select {
          .el-input__wrapper {
            border-radius: 6px;
            background-color: var(--card-bg-color);
          }
        }
        
        .el-date-editor {
          .el-input__wrapper {
            border-radius: 6px;
            background-color: var(--card-bg-color);
          }
        }
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
  }
  
  .table-wrapper {
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    
    :deep(.el-card__header) {
      background-color: var(--header-bg-color);
      border-bottom: 1px solid var(--border-color);
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        span {
          color: var(--text-color);
          font-weight: 600;
          font-size: 16px;
        }
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
    
    :deep(.el-card__body) {
      background-color: var(--card-bg-color);
      padding: 20px;
    }
    
    :deep(.el-table) {
      border-radius: 6px;
      overflow: hidden;
      background-color: var(--card-bg-color);
      
      .el-table__header {
        th {
          background-color: var(--header-bg-color);
          color: var(--text-color);
          font-weight: 600;
          border-bottom: 1px solid var(--border-color);
        }
      }
      
      .el-table__body {
        tr {
          background-color: var(--card-bg-color);
          
          &:hover > td {
            background-color: var(--hover-bg-color) !important;
          }
          
          td {
            border-bottom: 1px solid var(--border-color);
            color: var(--text-color);
            
            .el-tag {
              border-radius: 4px;
              font-weight: 500;
            }
            
            .el-button {
              border-radius: 4px;
              font-weight: 500;
              transition: all 0.3s ease;
              color: var(--text-color);
              
              &:hover {
                transform: translateY(-1px);
              }
            }
          }
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    
    :deep(.el-pagination) {
      .el-pager li {
        border-radius: 4px;
        margin: 0 2px;
        transition: all 0.3s ease;
        background-color: var(--card-bg-color);
        color: var(--text-color);
        
        &:hover {
          background-color: var(--hover-bg-color);
        }
        
        &.is-active {
          background-color: #409eff;
          color: #ffffff;
        }
      }
      
      .btn-prev,
      .btn-next {
        border-radius: 4px;
        transition: all 0.3s ease;
        background-color: var(--card-bg-color);
        color: var(--text-color);
        
        &:hover {
          background-color: var(--hover-bg-color);
        }
      }
    }
  }
  
  .form-tip {
    font-size: 12px;
    color: var(--text-color);
    margin-top: 5px;
    line-height: 1.4;
  }
}

// 对话框样式优化
:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  background-color: var(--card-bg-color);
  
  .el-dialog__header {
    background-color: var(--header-bg-color);
    border-bottom: 1px solid var(--border-color);
    border-radius: 8px 8px 0 0;
    
    .el-dialog__title {
      color: var(--text-color);
      font-weight: 600;
    }
  }
  
  .el-dialog__body {
    background-color: var(--card-bg-color);
    padding: 24px;
    color: var(--text-color);
    
    .el-descriptions {
      background-color: var(--card-bg-color);
      
      .el-descriptions__header {
        background-color: var(--header-bg-color);
      }
      
      .el-descriptions__body {
        background-color: var(--card-bg-color);
        
        .el-descriptions__table {
          .el-descriptions__cell {
            border-color: var(--border-color);
            
            &.is-bordered-label {
              background-color: var(--header-bg-color);
              color: var(--text-color);
              font-weight: 500;
            }
            
            &.is-bordered-content {
              background-color: var(--card-bg-color);
              color: var(--text-color);
            }
          }
        }
      }
    }
    
    .el-divider {
      border-color: var(--border-color);
      
      .el-divider__text {
        background-color: var(--card-bg-color);
        color: var(--text-color);
        font-weight: 500;
      }
    }
    
    .el-textarea {
      .el-textarea__inner {
        border-radius: 6px;
        border-color: var(--border-color);
        background-color: var(--card-bg-color);
        color: var(--text-color);
        
        &:focus {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }
    }
    
    .el-form {
      .el-form-item {
        margin-bottom: 20px;
        
        .el-form-item__label {
          color: var(--text-color);
          font-weight: 500;
        }
        
        .el-input-number {
          .el-input__wrapper {
            border-radius: 6px;
            transition: all 0.3s ease;
            background-color: var(--card-bg-color);
            
            &:hover {
              border-color: var(--border-color);
            }
            
            &.is-focus {
              border-color: #409eff;
              box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
            }
          }
        }
      }
    }
  }
  
  .el-dialog__footer {
    background-color: var(--header-bg-color);
    border-top: 1px solid var(--border-color);
    border-radius: 0 0 8px 8px;
    
    .dialog-footer {
      .el-button {
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
      }
    }
  }
}
</style>
